import * as crypto from 'crypto';

export interface ICryptoProps {
    password: string
    encode: string
}

export interface IData {
    [index:string]:string
}

/*
* 主要负责对字符串进行加密,解密
* */
export default class MyCrypto{
    private readonly password:string = '咖啡猫的密码';
    private readonly encode:string = 'utf8';

    constructor(props?:ICryptoProps){
        if(props!==undefined){
            const {password, encode} = props;
            this.password = password;
            this.encode = encode;
        }
    }

    dataEncode(DATA:IData):IData{
        const keys = Object.keys(DATA);
        let encodeData:IData = {};
        for(let i=0,length=keys.length;i<length;i++){
            const key = keys[i];
            if(typeof DATA[key]!=='string'){
                DATA[key] = String(DATA[key]);
            }
            encodeData[key] = this.strEncode(DATA[key]);
        }
        return encodeData;
    }


    dataDecode(DATA:IData):IData{
        const keys = Object.keys(DATA);
        let encodeData:IData = {};
        for(let i=0,length=keys.length;i<length;i++){
            const key = keys[i];
            encodeData[key] = this.strDecode(DATA[key]);
        }
        return encodeData;
    }

    /**
     * 字符串加密,便于存入数据库
     * @param str {string } 要加密的字符串
     * @return result {string} 返回加密过的字符串
     * */
    strEncode(str:string) {
        let cipher1 = crypto.createCipher('aes192', this.password);
        /*
        * 第一个参数是要加密的字符串,第二个是输入编码,第三个是输出编码
        * */
        let encrypted = cipher1.update(str,'utf8','hex');
        /*final函数返回加密后的数据*/
        encrypted += cipher1.final('hex');
        return  encrypted;
    };

    /**
     * 字符串解密,便于前端使用
     * @param str {string }要解密的字符串
     * @return result {string} 返回解密过的字符串
     * */
    strDecode(str:string) {
        let decipher = crypto.createDecipher('aes192', this.password);
        let decrypted = decipher.update(str, 'hex', 'utf8');
        decrypted += decipher.final('utf8');
        return decrypted;
    };

}